<?php


namespace app\api\logic;


use app\common\logic\BaseLogic;
use app\common\service\PasswordService;
use app\model\Third;
use app\model\user\User;
use common\service\JwtService;
use Exception;
use plugin\colewechat\app\service\AccountService;
use support\exception\BadException;
use support\utils\Time;
use Webman\Event\Event;

class LoginLogic extends BaseLogic
{
    /**
     * @var UserLogic
     */
    private UserLogic $userLogic;

    public function __construct()
    {
        $this->model = new User();
    }

    public function loginByAccount($input)
    {
        $username = $input['username'];
        $password = $input['password'];
        $user = User::where([
            'username' => $username
        ])->field(['id', 'password', 'salt', 'status'])->find();
        if (!$user) {
            throw new BadException("账号密码错误");
        }
        if ($user['status'] != 0) {
            throw new BadException("账号已经被禁用");
        }
        if (!PasswordService::checkPassword($password, $user['password'], $user['salt'])) {
            throw new BadException("账号密码错误");
        }
        $token = JwtService::generateToken($user['id'], 'api');
        $user->ip = request()->getRealIp();
        $user->login_time = Time::now();
        $user->save();
        return [
            "tokenName" => "Authorization",
            'tokenValue' => $token,
        ];
    }

    public function loginByMobile($input)
    {
        $username = $input['username'];
        $code = $input['code'];
        //验证验证码
        if ($code != 1234) {
            throw new BadException("验证码错误");
        }
        $user = User::where([
            'mobile' => $username
        ])->field(['id', 'password', 'salt', 'status'])->find();
        if (!$user) {
            throw new BadException("账号密码错误");
        }
        if ($user['status'] != 0) {
            throw new BadException("账号已经被禁用");
        }


        $user->ip = request()->getRealIp();
        $user->login_time = Time::now();
        $user->save();

        $token = JwtService::generateToken($user['id'], 'api');
        return [
            "tokenName" => "Authorization",
            'tokenValue' => $token
        ];
    }

    public function loginByCode($code, $invite_id)
    {
        $acc = new AccountService();
        try {
            $auth = $acc->getUserInfoByCode($code);
        } catch (Exception $exception) {
            throw new BadException("接口错误:" . $exception->getMessage());
        }

        $third = Third::where([
            'openid' => $auth['id'],
        ])
            ->find();
        $user_id = $third['user_id'] ?? 0;
        $isRegister = false;
        if (!$third) {
            $user_id = $this->register([
                "username" => $auth['name'] ?? "",
                "nickname" => $auth['nickname'] ?? "",
                "email" => $auth['email'] ?? "",
                "avatar" => $auth['avatar'] ?? "",
                "invite_id" => $invite_id,
                "source" => User::SOURCE_H5,
            ]);
            $model = new Third();
            $model->save([
                "user_id" => $user_id,
                "platform" => "mp",
                "app_type" => "mp",
                "openid" => $auth['id'],
                "open_name" => $auth['name'] ?? "",
            ]);
            $isRegister = true;
        }
        $user = User::where(['id' => $user_id])->find();
        if ($isRegister) {
            Event::dispatch('user.register.success', $user);
        }
        $user->ip = request()->getRealIp();
        $user->save();
        $token = JwtService::generateToken($user['id'], 'api');
        return [
            "tokenName" => "Authorization",
            'tokenValue' => $token
        ];
    }

    private function register($userInfo)
    {
        $user = array_merge([
            "username" => "",
            "nickname" => "",
            "email" => "",
            "mobile" => "",
            "avatar" => "",
            "join_ip" => request()->getRealIp(),
            "join_time" => Time::now(),
        ], $userInfo);
        $model = new User();
        $model->save($user);
        return $model->id;
    }

}